<?php

namespace app\common\tools;

use app\admin\model\StoragePosition;
use League\Flysystem\Sftp\SftpAdapter;
use League\Flysystem\Adapter\Ftp as FtpAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use Overtrue\Flysystem\Qiniu\QiniuAdapter;
use think\facade\App;

class FileHandlerTools
{

    protected $modelPosition;

    /**
     * flysystem instance
     *
     * @var Filesystem
     */
    protected $flysystem;

    public static function buildInstance(StoragePosition $model_position)
    {
        return new static($model_position);
    }

    public function __construct(StoragePosition $model_position)
    {
        $this->modelPosition = $model_position;
        $this->initFlysystem();
    }

    public function getFlysystem()
    {
        return $this->flysystem;
    }

    public function buildPath($path)
    {
        return $this->modelPosition->prefix_path . '/' . $path;
    }

    protected function initFlysystem()
    {

        $type = $this->modelPosition->type;

        $adpter = null;

        switch ($type) {
            case 'sftp':
                $adpter = new SftpAdapter([
                    'host' => $this->modelPosition->config->host,
                    'port' => $this->modelPosition->config->port,
                    'username' => $this->modelPosition->config->username,
                    'password' => $this->modelPosition->config->password,
                    'root' => $this->modelPosition->config->root

                ]);
                break;

            case 'ftp':
                $adpter = new FtpAdapter([
                    'host' => $this->modelPosition->config->host,
                    'username' => $this->modelPosition->config->username,
                    'password' => $this->modelPosition->config->password,
                    'port' => $this->modelPosition->config->port,
                    'root' => $this->modelPosition->config->root,
                    'ssl' => $this->modelPosition->config->ssl,
                    'passive' => $this->modelPosition->config->passive
                ]);

                break;
            case 'local':
                $adpter = new Local($this->modelPosition->config->path);
                break;
            case 'site':

                $path = App::getRootPath() . '/data/storage/position/';

                $adpter = new Local($path);
                break;

            case 'qiniu':
                $adpter = new QiniuAdapter(
                    $this->modelPosition->config->access_key,
                    $this->modelPosition->config->secret_key,
                    $this->modelPosition->config->bucket,
                    $this->modelPosition->config->domain,
                );
                break;

            default:
                # code...
                break;
        }


        $flysystem = new Filesystem($adpter);
        $this->flysystem = $flysystem;
        return $flysystem;
    }
}
